package com.xuecheng.comment.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.api.comment.model.dto.CommentReplyDTO;
import com.xuecheng.api.comment.model.vo.CommentReplyVO;
import com.xuecheng.comment.common.constant.CommentErrorCode;
import com.xuecheng.comment.convert.CommentReplyConvert;
import com.xuecheng.comment.entity.Comment;
import com.xuecheng.comment.entity.CommentReply;
import com.xuecheng.comment.mapper.CommentReplyMapper;
import com.xuecheng.comment.service.CommentReplyService;
import com.xuecheng.comment.service.CommentService;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import com.xuecheng.comment.service.CommentReplyService;
import com.xuecheng.comment.entity.CommentReply;
import com.xuecheng.comment.mapper.CommentReplyMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CommentReplyServiceImpl extends ServiceImpl<CommentReplyMapper, CommentReply> implements CommentReplyService {

    @Autowired
    private CommentService commentService;

    @Transactional
    public CommentReplyDTO replyMsg(CommentReplyVO commentReplyVO) {
        //判断关键数据
        //判断评论信息
        Long commentId = commentReplyVO.getCommentId();
        if (ObjectUtils.isEmpty(commentId)) {
            ExceptionCast.cast(CommentErrorCode.E_180008);
        }
        String reply = commentReplyVO.getReplyText();
        if (StringUtil.isBlank(reply)) {
            ExceptionCast.cast(CommentErrorCode.E_180009);
        }
        //判断评论是否允许回复
        Comment comment = commentService.getById(commentId);
        if (!("1".equals(comment.getForbidReply().toString()))) {
            ExceptionCast.cast(CommentErrorCode.E_180100);
        }
        //信息映射
        CommentReply commentReply = new CommentReply();
        commentReply.setCommentId(commentId);
        commentReply.setParentId(commentId);
        commentReply.setUserId(comment.getUserId());
        commentReply.setUserName(comment.getUserName());
        commentReply.setReplyText(reply);
        commentReply.setStatus(1);
        commentReply.setReplyDate(LocalDateTime.now());
        //将信息保存到数据库并保存

        boolean save = this.save(commentReply);
        //判断保存是否成功
        if (!save) {
            ExceptionCast.cast(CommentErrorCode.E_180101);
        }
        //数据转换并返回
        CommentReplyDTO commentReplyDTO = CommentReplyConvert.INSTANCE.entity2dto(commentReply);
        return commentReplyDTO;
    }

}
